package gui;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.border.TitledBorder;

import domain.Game;
import domain.models.GamesTableModel;

public class GamesPanel extends JPanel{
	
	private Frame frame;
	private GuiController guiController;
	
	private JTable gamesTable;
	
	private boolean areInProgress;
	private String title;
	
	public GamesPanel(Frame frame, boolean areInProgress)
	{
		super();
		this.frame = frame;
		this.guiController = frame.getGuiController();
		this.areInProgress = areInProgress;
		title = (areInProgress ? "Partijen die bezig zijn" : "Partijen die gespeeld zijn");
		
		initGUI();
	}
	
	private void initGUI()
	{
		gamesTable = new JTable(new GamesTableModel(guiController.getDomainController(), areInProgress));
		gamesTable.getColumnModel().getColumn(2).setCellEditor(new MyComboBoxEditor(new String[]{"0-1", "0,5-0,5", "1-0"}));
		
		JScrollPane scrollableGamesTable = new JScrollPane(gamesTable);
		scrollableGamesTable.setVisible(true);
		scrollableGamesTable.setBorder(new TitledBorder(title));
		
		this.add(scrollableGamesTable);
		JButton applyChangesBtn = new JButton("Wijzigingen toepassen");
		applyChangesBtn.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				for(int rowI = 1; rowI <= gamesTable.getRowCount(); rowI++)
				{
					JComboBox cmbBxResult = (JComboBox) gamesTable.getModel().getValueAt(rowI, 3);
					String selectedResult = cmbBxResult.getSelectedItem().toString();
					String[] formattedSelectedResult = new String[2];
					if((selectedResult.isEmpty()))
					{
						formattedSelectedResult = selectedResult.split("-");
						guiController.getDomainController().saveResult(Integer.parseInt((String) gamesTable.getModel().getValueAt(rowI, 4)), formattedSelectedResult, areInProgress);
					}
				}
			}
			
		});
		this.add(applyChangesBtn);
	}
	
	class MyComboBoxEditor extends DefaultCellEditor {
	    public MyComboBoxEditor(String[] items) {
	        super(new JComboBox(items));
	    }
	}

}
